﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Komunikator.Web;

namespace Komunikator.Views
{
    public partial class AddNewContactWindow : ChildWindow
    {
        public AddNewContactWindow()
        {
            InitializeComponent();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            var context = new CommunicatorDomainContext();
            var getContactList = context.Load(context.GetContactListByUserNameQuery(WebContext.Current.User.Name));
            getContactList.Completed += (s, ve) =>
                {
                    var addNewContactInfo = (AddNewContactInfo)this.DataContext;
                    var contactList = (ContactLists)getContactList.Entities.FirstOrDefault();
                    if (contactList != null)
                    {
                        contactList.Contacts.Add(new Contacts
                        {
                            ContactListId = contactList.ContactListId,
                            FirstName = addNewContactInfo.FirstName,
                            LastName = addNewContactInfo.LastName,
                            DisplayName = addNewContactInfo.DisplayedName,
                            UserName = addNewContactInfo.UserName
                        });
                        var saveContact = context.SubmitChanges();
                        saveContact.Completed += (s2, ve2) =>
                            {
                                if (saveContact.HasError)
                                {
                                    MessageBox.Show("Wystąpił błąd przy dodawaniu kontaktu: " + saveContact.Error.Message);
                                }
                            };
                    }
                    else
                    {
                        MessageBox.Show("Aby dodać kontakt do listy kontaktów musisz być zalogowany!");
                    }
                };
            
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
    }
}

